const http=require('http')
const fs=require('fs')
const path=require('path')
const url=require('url')
const cheerio = require('cheerio')

var filePath=path.join(__dirname,'/news.html')
var htmlStr=''
fs.readFile(filePath,(err,data)=>{
    if(err){
        console.log(err)
    }
    else{
        htmlStr+=data
    }   
})

http.createServer((req,res)=>{
    var urlObj=url.parse(req.url)
    var pathname=urlObj.pathname
    var talents=[]
    if(pathname=='/'){
        var $=cheerio.load(htmlStr)
        $('.news-model').each((i,ele)=>{
            if($(ele).children('span').text().slice(1,5)==2018){
                var newsTitle=$(ele).children('a').children('b').text()
                var createTime=$(ele).children('span').text().slice(1,-1)
                var newsObj={newsTitle:newsTitle,createTime:createTime}
                talents.push(newsObj)
            }
        })
        console.log(htmlStr)
        res.writeHead(200,{"Content-Type":"text/json;charset:utf8"})
        res.write(JSON.stringify(talents))
        res.end()
    }
}).listen(8081)